import request from "@/axios/request";
import { ElMessage } from "element-plus";

export default {
    name: "HouseDisplay",
    data() {
        return {
            loading: true,
            Data: {},
            isFavorited: false,
            tenantId: '',
            comments: [], // 存储当前房源的评论列表
            userMap: {},
            commentCount: 0, // 评论数量
            rating: 0, // 评分
            colors: ['#99A9BF', '#F7BA1E', '#FF9900'] ,// 评分星星的颜色，2，3，4是颜色分界
            // 状态映射
            statusMap: {
                rented: { text: '已租', type: 'info' },
                available: { text: '待租', type: 'success' },
                pending: { text: '审核中', type: 'warning' },
                rejected: { text: '审核未通过', type: 'danger' }
            },
        };
    },
    created() {
        const houseId = this.$route.query.houseId;
        this.load(houseId);
        this.loadComments(houseId);
        this.loading = true;
        //获取当前登录用户ID(TenantSelfInfo)
        const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo') || '{}');
        this.tenantId = userInfo.tenantId || ''; // 从sessionStorage中提取tenantId
        this.loadFavoriteStatus(houseId,this.tenantId);
    },
    methods: {
        // 房屋详情
        async load(houseId) {
            this.loading = true;
            try{
                const res = await request.get(`/house/${houseId}`);
                if (res.code === 200) {
                    // 保留原始状态码，新增 displayStatus 字段用于显示
                    this.Data = res.data;  
                    this.Data.displayStatus = this.statusMap[this.Data.status]?.text || '未知状态';
                    
                }else {
                    ElMessage.error(res.msg || "加载失败");
                    this.Data = {};
                }
            } catch (err){
                console.error(err);
                ElMessage.error("网络错误，请稍后再试");
            } finally {
                this.loading = false; // 接口请求完成后关闭loading
            }
        },
        // 评论列表
        async loadComments(houseId) {
            try {
                // 先清空旧数据
                this.userMap = {};
                this.comments = [];
                this.commentCount = 0;

                const res = await request.get(`/comment/house/${houseId}`);

                // 如果接口调用失败，直接提示并 return
                if (res.code !== 200) {
                // ElMessage.error(res.msg || '加载评论失败');
                return;
                }

                // 此时 res.code === 200
                const list = Array.isArray(res.data) ? res.data : [];

                // 只有在确实有评论时才去拉用户名
                if (list.length > 0) {
                // 并行请求所有用户名
                await Promise.all(
                    list.map(async (comment) => {
                    try {
                        const userRes = await request.get(`/tenant/findById/${comment.tenantId}`);
                        // 强制转成字符串 key，以防类型不一致
                        this.userMap[String(comment.tenantId)] = (userRes.code === 200 && userRes.data.username) || '匿名用户';
                    } catch {
                        this.userMap[String(comment.tenantId)] = '匿名用户';
                    }
                    })
                );
                }

                // 最后赋值评论列表
                this.comments = list;
                this.commentCount = list.length;

            } catch (err) {
                console.error("加载评论失败：", err);
                ElMessage.error("加载评论失败，请稍后重试");
            }
        },

        //时间显示
        formatDate(dateStr) {
            if (!dateStr) return "";
            const date = new Date(dateStr);
            return date.toLocaleString("zh-CN", {
                year: "numeric",
                month: "2-digit",
                day: "2-digit",
                hour: "2-digit",
                minute: "2-digit",
            });
        },
        async loadFavoriteStatus(houseId, tenantId) {
            try {
                const res = await request.post(`/favorite/tenantAndHouse` ,{
                    tenantId: tenantId,
                    houseId: houseId
                    });
                if (res.code === 200) {
                this.isFavorited = true;
                }else if (res.code === 404) {
                this.isFavorited = false;
                }
            } catch (err) {
                console.error("获取收藏状态失败：", err);
            }
        },

        // 切换收藏/取消收藏
        async handleFavorite() {
            // 先乐观更新
            try {
                if (this.isFavorited) {
                    await request.delete("/favorite/cancel", {
                    data: {
                        houseId: this.Data.houseId,
                        tenantId: this.tenantId
                        }
                    });
                }else {
                    await request.post("/favorite/add", {
                    houseId: this.Data.houseId,
                    tenantId: this.tenantId
                    });
                }
                console.log(this.tenantId);
                this.isFavorited = !this.isFavorited;
                ElMessage.success(this.isFavorited ? "已收藏" : "已取消收藏");
            } catch (err) {
                // 回滚
                this.isFavorited = !this.isFavorited;
                console.error(err);
                ElMessage.error("操作失败，请重试");
            }
        },
        // 提交评论
        async subComment() {
            // 判断用户是否评论过
            const hasCommented = this.comments.some(
                comment => String(comment.tenantId) === String(this.tenantId)//判断用户名是否已存在
            );
            if (hasCommented) {
                ElMessage.warning('用户仅允许提交一次评论');
                this.commentContent = '';
                this.rating = 0;
                return; 
            }
            try {
                // 构建评论数据
                const commentData = {
                    houseId: this.$route.query.houseId,
                    tenantId: this.tenantId,
                    content: this.commentContent.trim(),
                    rating: this.rating
                };
                // 调用后端接口
                const res = await request.post(`/comment/add`, commentData);
                if (res.code === 200) {
                    // 评论成功
                    ElMessage.success('评论提交成功');
                    
                    // 清空表单
                    this.commentContent = '';
                    this.rating = 0;
                    
                    // 刷新评论列表
                    await this.loadComments(this.$route.query.houseId);
                } else {
                    // 评论失败
                    ElMessage.error(res.msg || '评论提交失败');
                }
            } catch (err) {
                console.error("提交评论错误：", err);
                ElMessage.error('网络错误，请稍后再试');
            }
        },
        async subapplication(){
            //判断房源的状态
            const res = await request.get(`/house/${this.Data.houseId}`);
            if (res.code === 200 && res.data.status !== "available") {
                ElMessage.warning('该房源已不可申请');
                return;
            }
            try {
                //申请数据
                const res = await request.post(`/rental/apply`, {
                    houseId: this.Data.houseId,
                    tenantId: this.tenantId,
                    type: "in",
                    
                });
                if (res.code === 200) {
                    ElMessage.success('申请提交成功');
                } else {
                    ElMessage.error(res.msg || '申请提交失败');
                }
            } catch (err) {
                console.error("提交申请错误：", err);
                ElMessage.error('网络错误，请稍后再试');
            }
        },
        // 状态标签类型获取方法
        getStatusTagType(status) {
            return this.statusMap[status]?.type || '';
        },
        // 状态标签文本获取方法
        getStatusLabel(status) {
            return this.statusMap[status]?.text || '未知状态';
        }
    },
};